package com.zzuli.practice.service.impl;

import com.google.code.kaptcha.Producer;
import com.zzuli.practice.controller.LoginController;
import com.zzuli.practice.entity.Code;
import com.zzuli.practice.entity.LoginToken;
import com.zzuli.practice.entity.Result;
import com.zzuli.practice.entity.User;
import com.zzuli.practice.mapper.UserMapper;
import com.zzuli.practice.service.ILoginService;
import com.zzuli.practice.util.Constant;
import com.zzuli.practice.util.JWTUtils;
import com.zzuli.practice.util.PracticeUtil;
import org.apache.axis.encoding.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Service
public class LoginService implements Constant , ILoginService {


    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private UserMapper userMapper;

    public User selectByName(String username){
        return userMapper.selectByName(username);
    }

    public Code getKaptcha(HttpServletResponse response, HttpServletRequest request){
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        Code code = new Code();

        // 将验证码存入session
//        HttpSession session = request.getSession();
//        session.setAttribute("kaptcha", text);
//        System.out.println(request.getSession().getAttribute("kaptcha"));

        System.out.println("刷新验证码");


        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
//            OutputStream os = response.getOutputStream();// 由spring MVC来维护，不需要关闭
            ImageIO.write(image, "png", os);
            String encode = Base64.encode(os.toByteArray());
            code.setCode(text);
            code.setCodeimg(encode);
        } catch (IOException e) {
            logger.error("响应验证码失败:" + e.getMessage());
        }
        return code;
    }

    public User selectByUserName(String username){
        return userMapper.selectByName(username);
    }


}
